<script setup>
import { ref, computed, watch } from 'vue';
import { Edit, Delete, Plus } from '@element-plus/icons-vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

//导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

const route = useRoute(); // 获取当前路由对象
const my_s_id = ref(route.query.user_Id); // 从路由的 query 中提取 学号 并保存为响应式变量


// 抽屉状态
const visibleDrawer = ref(false);

// 控制弹窗显示的变量
const dialogVisible = ref(false);
const commentContent = ref('');

// 搜索考试的信息表单
const searchExamData = ref({
    s_id: my_s_id.value,
    e_name: ''
})

// 排序方式
const sorting = ref('按ID 降序'); // 默认排序方式


// 弹窗显示方法
const showComment = (comment) => {
    commentContent.value = comment;  // 设置评语内容
    dialogVisible.value = true;      // 显示弹窗
};

// 示例数据
const myexams = ref([
    {
        "e_id": 1,
        "e_name": "期中考试",
        "startTime": "2024-11-01 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷1",
        "s_score": null, // 本场考试的得分
        "s_comment": "阿斯顿法国红酒看来是的风格和健康脸上的瑕疵v不那么，大润发天涯海角看来下次v不那么现场v不那么，的风格和健康", // 教师的评语
    },
    {
        "e_id": 2,
        "e_name": "期末考试",
        "startTime": "2024-12-15 09:30:00",
        "endTime": "2024-12-15 12:30:00",
        "q_path": "/files/exam2.pdf",
        "q_name": "试卷2",
        "s_score": null, // 本场考试的得分
        "s_comment": "", // 教师的评语
    },
    {
        "e_id": 3,
        "e_name": "最后的考试",
        "startTime": "2024-11-05 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷3",
        "s_score": null, // 本场考试的得分
        "s_comment": "", // 教师的评语
    },
    {
        "e_id": 4,
        "e_name": "期中考试",
        "startTime": "2024-11-01 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷1",
        "s_score": null, // 本场考试的得分
        "s_comment": "", // 教师的评语
    },
    {
        "e_id": 5,
        "e_name": "期末考试",
        "startTime": "2024-12-15 09:30:00",
        "endTime": "2024-12-15 12:30:00",
        "q_path": "/files/exam2.pdf",
        "q_name": "试卷2",
        "s_score": null, // 本场考试的得分
        "s_comment": "", // 教师的评语
    },
    {
        "e_id": 6,
        "e_name": "最后的考试",
        "startTime": "2024-11-05 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷3",
        "s_score": null, // 本场考试的得分
        "s_comment": "", // 教师的评语
    },
    {
        "e_id": 7,
        "e_name": "期中考试",
        "startTime": "2024-11-01 10:00:00",
        "endTime": "2024-12-01 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷1",
        "s_score": null, // 本场考试的得分
        "s_comment": "", // 教师的评语
    },
    {
        "e_id": 8,
        "e_name": "期末考试",
        "startTime": "2024-12-15 09:30:00",
        "endTime": "2024-12-15 12:30:00",
        "q_path": "/files/exam2.pdf",
        "q_name": "试卷2",
        "s_score": null, // 本场考试的得分
        "s_comment": "", // 教师的评语
    },
    {
        "e_id": 9,
        "e_name": "最后的考试",
        "startTime": "2024-11-05 10:00:00",
        "endTime": "2024-12-10 15:00:00",
        "q_path": "/files/exam1.pdf",
        "q_name": "试卷3",
        "s_score": null, // 本场考试的得分
        "s_comment": "", // 教师的评语
    },
]);

// 排序后的考试数据
const sortedExams = computed(() => {
    let sortedData = [...myexams.value]; // 创建数据副本以避免修改原始数据

    // 根据排序方式排序
    switch (sorting.value) {
        case '按ID 升序':
            sortedData.sort((a, b) => a.e_id - b.e_id);
            break;
        case '按ID 降序':
            sortedData.sort((a, b) => b.e_id - a.e_id);
            break;
        case '按截止时间 升序':
            sortedData.sort((a, b) => new Date(a.endTime) - new Date(b.endTime));
            break;
        case '按截止时间 降序':
            sortedData.sort((a, b) => new Date(b.endTime) - new Date(a.endTime));
            break;
        default:
            break;
    }

    return sortedData;
});

// 排序函数
const sortExams = () => {
    // 排序逻辑已在computed中处理，所以只需触发重新渲染
};

// 分页后的考试数据
const paginatedMyExams = computed(() => {
    const start = (pageNum.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return sortedExams.value.slice(start, end);
});

// 考试提交答卷的数据模型
const submitExamData = ref({
    s_id: my_s_id.value,  // 本人学号
    e_id: null,           // 考试的id
    e_name: '',           // 考试名称
    s_fpath: '',          // 答卷的下载路径
    s_fname: '',          // 答卷的名称
})

// 清空数据模型的表单
const resetForm = () => {
    submitExamData.value = {
        s_id: my_s_id.value,  // 本人学号
        e_id: null,           // 考试的id
        e_name: '',           // 考试名称
        s_fpath: '',          // 答卷的下载路径
        s_fname: '',          // 答卷的名称
    }
};

//声明一个异步的函数
import { examListForStudentService, examSearchForStudentService } from '@/api/examNew.js'
// 获取考试列表
const getMyExamList = async () => {
    try {
        let result = await examListForStudentService(my_s_id.value);
        myexams.value = result.data;
    } catch (error) {

    }
}

// 调用
getMyExamList();

// 搜索考试
const searchExamByName = async () => {
    try {
        let result = await examSearchForStudentService(searchExamData.value);
        myexams.value = result.data;
    } catch (error) {

    }
};

import { studentSubmitExamService } from '@/api/student.js'

// 向服务器提交答卷
const submitExam = async () => {
    try {
        // 调用学生信息修改接口
        let result = await studentSubmitExamService(submitExamData.value);
        // 根据服务端返回的msg信息是否为空，判断是否更新成功
        ElMessage.success(result.msg ? result.msg : '答卷已上传');
        // 刷新考试列表
        getMyExamList();
    } catch (error) {
        ElMessage.error('上传答卷请求超时');
    }
    closeDrawer();
}

// 点击打开抽屉
const openDrawer = (row) => {
    resetForm();
    submitExamData.value.e_id = row.e_id;
    submitExamData.value.e_name = row.e_name;

    visibleDrawer.value = true;
};

// 关闭抽屉
const closeDrawer = () => {
    resetForm();
    visibleDrawer.value = false;
};

// 按下抽屉中“保存”键后，根据情景不同调用相关函数
const handleSubmit = () => {
    submitExam();

};

// 文件错误信息
const errorMsg = ref('');

// 检测上传信息是否完整，以判断是否能够提交请求
const canSubmit = computed(() => {
    return (
        submitExamData.value.s_id &&
        submitExamData.value.e_id &&
        submitExamData.value.e_name &&
        submitExamData.value.s_fname &&
        submitExamData.value.s_fpath
    );
});

// 校验文件类型和大小
const handleFileChange = (file, fileList) => {
    ElMessage.success('上传文件改变触发')

    if (fileList.length === 0) {
        errorMsg.value = "";
        ElMessage.info("已清空");
        return;
    }

    const currentFile = fileList[0].raw;
    const validTypes = ["image/png", "image/jpeg", "application/zip", "application/x-7z-compressed", "application/x-rar-compressed"];
    const maxSize = 5 * 1024 * 1024; // 5MB

    if (!validTypes.includes(currentFile.type)) {
        errorMsg.value = "文件格式不正确，仅支持PNG、JPEG、ZIP、RAR、7Z";
        fileList.splice(0); // 清空文件列表
        return;
    }

    if (currentFile.size > maxSize) {
        errorMsg.value = "文件大小不能超过5MB";
        return;
    }

    errorMsg.value = "";
    submitExamData.value.s_fname = currentFile.name; // 设置答卷名称
    submitExamData.value.s_fpath = currentFile.url || currentFile.response?.path; // 设置答卷下载路径

    if (uploadRef.value) {
        uploadRef.value.submit(); // 手动触发上传
    }
};

// 上传文件成功回调
const uploadFileSuccess = (result) => {
    ElMessage.success('文件上传成功');
    submitExamData.value.s_fpath = result.data; // 设置答卷下载路径
};



// 根据考试时间判断考试状态
const calculateExamStatus = (startTime, endTime) => {
    const now = new Date();
    const start = new Date(startTime);
    const end = new Date(endTime);

    if (now < start) return "未开始";
    if (now >= start && now <= end) return "进行中";
    return "已结束";
};

// 根据考试状态设置字体样式
const getStatusClass = (status) => {
    switch (status) {
        case "未开始":
            return "status-blue";
        case "进行中":
            return "status-green";
        case "已结束":
            return "status-red";
        default:
            return "";
    }
};

// 根据得分多少设置字体样式
const getScoreClass = (score) => {
    if (score === null) return "";
    if (score >= 90) return "score-excellent";
    if (score >= 60) return "score-pass";
    return "score-fail";
};

// 分页数据
const pageNum = ref(1); // 当前页
const pageSize = ref(3); // 每页条数
const total = ref(myexams.value.length); // 总条数

// 页大小改变
const onSizeChange = (size) => {
    pageSize.value = size;
    pageNum.value = 1; // 重置到第一页
};

// 页码改变
const onPageChange = (page) => {
    pageNum.value = page;
};

// 监听 exams 数组变化，实时更新 total 值
watch(
    () => myexams.value,
    (newVal) => {
        total.value = newVal.length;
    },
    { deep: true }
);

</script>


<template>
    <el-card>
        <template #header>
            <div class="header">
                <h1>{{ '我的考试' }}</h1>
            </div>
        </template>

        <!-- 搜索表单 和 排序筛选方式-->
        <el-form inline :model=searchExamData>
            <el-form-item label="考试名称">
                <el-input v-model="searchExamData.e_name" placeholder="请输入考试名称" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchExamByName()"
                    :disabled="!searchExamData.e_name">搜索</el-button>
                <el-button  @click="getMyExamList()">重置</el-button>
            </el-form-item>
            <el-form-item label="排序方式：">
                <el-select placeholder="请选择" v-model="sorting" @change="sortExams">
                    <el-option label="按ID 降序" value="按ID 降序"></el-option>
                    <el-option label="按ID 升序" value="按ID 升序"></el-option>
                    <el-option label="按截止时间 降序" value="按截止时间 降序"></el-option>
                    <el-option label="按截止时间 升序" value="按截止时间 升序"></el-option>
                </el-select>
            </el-form-item>

        </el-form>
        <hr>

        <!-- 学生成绩表格 -->
        <el-table :data="paginatedMyExams" style="width: 100%">
            <el-table-column label="名称(ID)">
                <template #default="{ row }">
                    {{ row.e_name }}(ID:{{ row.e_id }})
                </template>
            </el-table-column>
            <el-table-column label="开始时间">
                <template #default="{ row }">{{ row.startTime }}</template>
            </el-table-column>
            <el-table-column label="结束时间">
                <template #default="{ row }">{{ row.endTime }}</template>
            </el-table-column>
            <el-table-column label="试卷">
                <template #default="{ row }">
                    <template v-if="row.q_path">
                        <a v-if="calculateExamStatus(row.startTime, row.endTime) !== '未开始'" :href="row.q_path"
                            :download="row.q_name">
                            {{ row.q_name }}
                        </a>
                        <template v-else>
                            <span>考试未开始</span>
                        </template>
                    </template>
                    <span v-else>未上传</span>
                </template>
            </el-table-column>
            <el-table-column label="考试状态">
                <template #default="{ row }">
                    <span :class="getStatusClass(calculateExamStatus(row.startTime, row.endTime))">
                        {{ calculateExamStatus(row.startTime, row.endTime) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="我的得分">
                <template #default="{ row }">
                    <span :class="getScoreClass(row.s_score)">
                        {{ row.s_score !== null ? row.s_score : '未评分' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="老师评语">
                <template #default="{ row }">
                    <span v-if="!row.s_comment">无</span>
                    <span v-else @click="showComment(row.s_comment)" style="color: blue; cursor: pointer;">
                        查看评语
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="上传答卷">
                <template #default="{ row }">
                    <el-tooltip v-if="calculateExamStatus(row.startTime, row.endTime) == '未开始'" content="考试未开始，无法上传答卷"
                        placement="top">
                        <el-button :icon="Edit" circle plain type="primary" :disabled="true"></el-button>
                    </el-tooltip>
                    <el-tooltip v-else-if="calculateExamStatus(row.startTime, row.endTime) == '已结束'"
                        content="考试已结束，无法上传答卷" placement="top">
                        <el-button :icon="Edit" circle plain type="primary" :disabled="true"></el-button>
                    </el-tooltip>
                    <el-button v-else :icon="Edit" circle plain type="primary" @click="openDrawer(row)"
                        :disabled="false"></el-button>
                </template>
            </el-table-column>

            <template #empty>
                <el-empty description="没有考试数据" />
            </template>
        </el-table>


        <!-- 分页条   5555-->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onPageChange" style="margin-top: 20px; justify-content: flex-end" />

        <!-- 评论弹窗 -->
        <el-dialog v-model="dialogVisible" title="教师评语" width="30%" class="custom-dialog">

            <el-form>
                <el-form-item prop="commentContent">
                    <el-input type="textarea" v-model="commentContent" :rows="4" maxlength="200" placeholder="请输入教师评语"
                        class="custom-input"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="dialogVisible = false">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" title="上传答卷" direction="rtl" size="40%">
            <!-- 上传答卷表单 -->
            <el-form :model="submitExamData" label-width="100px">
                <!-- 学号 -->
                <el-form-item label="本人学号" :rules="[{ required: true, message: '学号不可为空', trigger: 'blur' }]">
                    <el-input v-model="submitExamData.s_id" :disabled="true" placeholder="学号" />
                </el-form-item>

                <!-- 考试ID -->
                <el-form-item label="本考试ID" :rules="[{ required: true, message: '考试ID不可为空', trigger: 'blur' }]">
                    <el-input v-model="submitExamData.e_id" :disabled="true" placeholder="考试ID" />
                </el-form-item>

                <!-- 考试名称 -->
                <el-form-item label="考试名称" :rules="[{ required: true, message: '考试名称不可为空', trigger: 'blur' }]">
                    <el-input v-model="submitExamData.e_name" :disabled="true" placeholder="考试名称" />
                </el-form-item>

                <!-- 答卷名称 (根据文件上传后自动填充) -->
                <el-form-item label="答卷名称" :rules="[{ required: true, message: '答卷名称不可为空', trigger: 'blur' }]">
                    <el-input v-model="submitExamData.s_fname" :disabled="true" placeholder="答卷名称" />
                </el-form-item>

                <!-- 答卷下载路径 (根据文件上传后自动填充) -->
                <el-form-item label="下载路径" :rules="[{ required: true, message: '答卷下载路径不可为空', trigger: 'blur' }]">
                    <el-input v-model="submitExamData.s_fpath" :disabled="true" placeholder="答卷下载路径" />
                </el-form-item>

                <!-- 上传答卷文件 -->
                <el-form-item label="上传答卷" :rules="[{ required: true, message: '请上传答卷文件', trigger: 'change' }]">
                    <el-upload class="file-uploader" action="/api/upload" name="file"
                        :headers="{ 'Authorization': tokenStore.token }" :file-list="fileList" :auto-upload="false"
                        :limit="1" :on-change="handleFileChange" ref="uploadRef" :on-success="uploadFileSuccess">
                        <el-button slot="trigger" type="primary">选择答卷文件</el-button>
                    </el-upload>
                    <el-alert v-if="errorMsg" :title="errorMsg" type="error" show-icon closable
                        style="margin-top: 10px" />
                </el-form-item>

                <!-- 提交按钮 -->
                <el-form-item>
                    <el-button :type="canSubmit ? 'primary' : 'info'" :disabled="!canSubmit" @click="handleSubmit">
                        {{ canSubmit ? '提交答卷' : '请完善信息' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>


<style scoped>
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.file-uploader {
    width: 100%;
}

/* 使标题居中 */
.custom-dialog .el-dialog__header {
    text-align: center;
    padding-left: 0;
    padding-right: 0;
    width: 100%;
}

/* 使底部按钮居中 */
.custom-dialog .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
    /* 按钮之间的间距 */
}

/* 使input组件与弹窗两侧的距离相同 */
.custom-input {
    padding-left: 20px;
    padding-right: 20px;
}

.upload-demo {
    margin: 10px 0;
}

.status-blue {
    color: rgb(26, 154, 214);
}

.status-green {
    color: rgb(26, 223, 118);
}

.status-red {
    color: rgb(234, 15, 15);
}

.score-excellent {
    color: green;
    font-weight: bold;
}

.score-pass {
    color: orange;
}

.score-fail {
    color: red;
    font-weight: bold;
}
</style>
